import React, { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { useAuthState } from 'react-firebase-hooks/auth';
import {
  collection,
  doc,
  getDoc,
  getDocs,
  query,
  where,
  orderBy,
} from 'firebase/firestore';
import { auth, db } from '../services/firebase';
import { User, Copywriting } from '../types';
import CopywritingCard from '../components/features/CopywritingCard';
import ProfileEditor from '../components/features/ProfileEditor';

const Profile = () => {
  const { userId } = useParams<{ userId: string }>();
  const [currentUser] = useAuthState(auth);
  const [profileUser, setProfileUser] = useState<User | null>(null);
  const [copywritings, setCopywritings] = useState<Copywriting[]>([]);
  const [favorites, setFavorites] = useState<Copywriting[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [showEditor, setShowEditor] = useState(false);
  const [activeTab, setActiveTab] = useState<'posts' | 'favorites'>('posts');

  useEffect(() => {
    const fetchUserData = async () => {
      if (!userId) return;

      try {
        setLoading(true);
        // 获取用户信息
        const userDoc = await getDoc(doc(db, 'users', userId));
        if (!userDoc.exists()) {
          setError('用户不存在');
          return;
        }
        setProfileUser({ uid: userDoc.id, ...userDoc.data() } as User);

        // 获取用户的文案
        const postsQuery = query(
          collection(db, 'copywriting'),
          where('authorId', '==', userId),
          where('status', '==', 'published'),
          orderBy('createdAt', 'desc')
        );
        const postsSnapshot = await getDocs(postsQuery);
        const postsData = postsSnapshot.docs.map(
          (doc) => ({ id: doc.id, ...doc.data() } as Copywriting)
        );
        setCopywritings(postsData);

        // 获取用户收藏的文案
        if (userDoc.data().favorites?.length > 0) {
          const favoritesData = await Promise.all(
            userDoc.data().favorites.map(async (id: string) => {
              const doc = await getDoc(doc(db, 'copywriting', id));
              return doc.exists()
                ? ({ id: doc.id, ...doc.data() } as Copywriting)
                : null;
            })
          );
          setFavorites(favoritesData.filter((doc): doc is Copywriting => doc !== null));
        }
      } catch (err) {
        console.error('Error fetching user data:', err);
        setError('加载失败');
      } finally {
        setLoading(false);
      }
    };

    fetchUserData();
  }, [userId]);

  const handleUpdateUser = (updatedUser: User) => {
    setProfileUser(updatedUser);
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center min-h-screen">
        <div className="text-lg">加载中...</div>
      </div>
    );
  }

  if (error || !profileUser) {
    return (
      <div className="max-w-3xl mx-auto px-4 py-8">
        <div className="text-red-600 text-center">{error || '用户不存在'}</div>
      </div>
    );
  }

  return (
    <div className="max-w-3xl mx-auto px-4 py-8">
      {/* 用户信息 */}
      <div className="bg-white rounded-lg shadow p-6 mb-8">
        <div className="flex items-start justify-between">
          <div className="flex items-center space-x-4">
            <img
              src={profileUser.photoURL || '/default-avatar.png'}
              alt={profileUser.displayName}
              className="w-20 h-20 rounded-full"
            />
            <div>
              <h1 className="text-2xl font-bold text-gray-900">
                {profileUser.displayName}
              </h1>
              <p className="text-gray-500 mt-1">{profileUser.email}</p>
              {profileUser.bio && (
                <p className="text-gray-700 mt-2">{profileUser.bio}</p>
              )}
            </div>
          </div>
          {currentUser?.uid === userId && (
            <button
              onClick={() => setShowEditor(true)}
              className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
            >
              编辑资料
            </button>
          )}
        </div>

        <div className="mt-6 grid grid-cols-3 gap-4 border-t border-gray-200 pt-4">
          <div className="text-center">
            <div className="text-2xl font-bold text-gray-900">
              {copywritings.length}
            </div>
            <div className="text-sm text-gray-500">文案</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-gray-900">
              {favorites.length}
            </div>
            <div className="text-sm text-gray-500">收藏</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-gray-900">
              {copywritings.reduce((sum, post) => sum + (post.likes || 0), 0)}
            </div>
            <div className="text-sm text-gray-500">获赞</div>
          </div>
        </div>
      </div>

      {/* 标签页切换 */}
      <div className="border-b border-gray-200 mb-6">
        <nav className="-mb-px flex space-x-8">
          <button
            onClick={() => setActiveTab('posts')}
            className={`pb-4 px-1 border-b-2 font-medium text-sm ${
              activeTab === 'posts'
                ? 'border-blue-500 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            文案 ({copywritings.length})
          </button>
          <button
            onClick={() => setActiveTab('favorites')}
            className={`pb-4 px-1 border-b-2 font-medium text-sm ${
              activeTab === 'favorites'
                ? 'border-blue-500 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            收藏 ({favorites.length})
          </button>
        </nav>
      </div>

      {/* 文案列表 */}
      <div className="grid grid-cols-1 gap-6">
        {activeTab === 'posts'
          ? copywritings.map((copywriting) => (
              <CopywritingCard key={copywriting.id} copywriting={copywriting} />
            ))
          : favorites.map((copywriting) => (
              <CopywritingCard key={copywriting.id} copywriting={copywriting} />
            ))}
        {((activeTab === 'posts' && copywritings.length === 0) ||
          (activeTab === 'favorites' && favorites.length === 0)) && (
          <div className="text-center py-8 text-gray-500">
            {activeTab === 'posts' ? '还没有发布文案' : '还没有收藏文案'}
          </div>
        )}
      </div>

      {/* 编辑个人资料对话框 */}
      {showEditor && (
        <ProfileEditor
          user={profileUser}
          onClose={() => setShowEditor(false)}
          onUpdate={handleUpdateUser}
        />
      )}
    </div>
  );
};

export default Profile;
